import {Context} from 'egg';
import * as _ from 'lodash';
// 无需token的地址
const noTokenUrl = [
    '/admin/comm/captcha' ,
    '/admin/comm/createQRCode' ,
    '/admin/comm/login' ,
    '/admin/comm/logout' ,
    '/admin/comm/upload' ,
    '/admin/comm/kuaidi/info' ,
    '/admin/goods/cate/list' ,
    '/admin/goods/brand/list' ,
    '/admin/goods/hotWords/list' ,
    '/admin/goods/tag/list' ,
    '/admin/goods/product/page' ,
    '/admin/goods/product/medias' ,
    '/admin/goods/product/info' ,
    '/admin/goods/recommend/page' ,
    '/admin/goods/recommend/list' ,
    '/admin/wx/user/page'];

const wxNoTokenUrl = [
    '/wx/product/info' ,
    '/wx/login' ,
    '/wx/createQRCode',
];

const wxValidataMobile = [
    '/wx/product/add' ,
    '/wx/product/update' ,
]

/**
 * 权限控制
 * @constructor
 */
export default function Authority () : any {
    return async (ctx : Context , next : () => Promise<any>) => {
        let statusCode = 200;
        const {url} = ctx;
        const token = ctx.get ('Authorization');
        if ( _.startsWith (url , '/admin') ) {
            // console.log('不用检测',url)
            // console.log(url.split('?')[0])
            if ( noTokenUrl.includes (url.split ('?')[0]) ) {
                // console.log('不用检测',url)
                await next ();
                return;
            }
            try {
                ctx.decoded = ctx.app.jwt.verify (token , ctx.app.config.jwt.secret);
                if ( ctx.decoded ) {
                    if ( _.startsWith (url , '/admin/comm/') ) {
                        await next ();
                        return;
                    }
                    const rToken = await ctx.app.redisGet (`admin:token:${ ctx.decoded.userId }`);
                    if ( !rToken ) {
                        ctx.status = 401;
                        ctx.body = {
                            code : 1001 ,
                            message : '登录失效或无权限访问~' ,
                        };
                        return;
                    }
                    if ( rToken !== token && ctx.app.config.SSO ) {
                        statusCode = 401;
                    } else {
                        // console.log('ctx.decoded',ctx.decoded)
                        // if(_.startsWith(url, '/admin/goods')){
                        //     statusCode = 200
                        // }else {

                        // }

                        // let perms = await ctx.app.redisGet(`admin:perms:${ ctx.decoded.userId }`);
                        // // console.log('perms',perms)
                        // if (!_.isEmpty(perms)) {
                        //     perms = JSON.parse(perms).map(e => {
                        //         return e.replace(/:/g, '/');
                        //     });
                        //     if (!perms.includes(url.split('?')[0].replace('/admin/', ''))) {
                        //         statusCode = 403;
                        //     }
                        // } else {
                        //     statusCode = 403;
                        // }
                    }
                }
            } catch (e) {
                statusCode = 401;
            }
            if ( statusCode > 200 ) {
                ctx.status = statusCode;
                ctx.body = {
                    code : 1001 ,
                    message : '登录失效或无权限访问~' ,
                };
                return;
            }
        }
        if ( _.startsWith (url , '/wx') ) {
            try {
                ctx.wx_decoded = ctx.app.jwt.verify (token , ctx.app.config.jwt.secret);
                if ( ctx.wx_decoded ) {
                    const wxToken = await ctx.app.redisGet (`wx:user:${ ctx.wx_decoded.id }`);
                    console.log ('测试登录成功没' , token , url);
                    if ( !wxToken || wxToken !== token) {
                        //不校验token
                        if ( wxNoTokenUrl.includes (url.split ('?')[0]) ) {
                            // ctx.wx_decoded = null
                            await next ();
                            return;
                        }
                        ctx.status = 401;
                        ctx.body = {
                            code : 1001 ,
                            message : '请重新登录' ,
                        };
                        return;
                    }
                    if ( wxToken === token ) {
                        if (wxValidataMobile.includes (url.split ('?')[0]) ) {
                            let info : any = await ctx.repo.wx.Wx_user.findOne ({id : ctx.wx_decoded.id});
                            if(ctx.app.config.wxAuthMobiles.includes(info.phoneNumber)){
                                await next();
                                return;
                            }else {
                                ctx.status = 403;
                                ctx.body = {
                                    code : 1001 ,
                                    message : '无权操作~' ,
                                };
                                return
                            }
                        }
                        await next();
                        return;
                    }
                }else {
                    if ( wxNoTokenUrl.includes (url.split ('?')[0]) ) {
                        // ctx.wx_decoded = null
                        await next ();
                        return;
                    }
                    statusCode = 401;
                }
            } catch (e) {
                //不校验token
                if ( wxNoTokenUrl.includes (url.split ('?')[0]) ) {
                    ctx.wx_decoded = null;
                    await next();
                    return;
                }
                statusCode = 401;
            }
            if ( statusCode === 401 ) {
                ctx.status = statusCode;
                ctx.body = {
                    code : 1001 ,
                    message : '请重新登录~' ,
                };
                return;
            }
        }
        await next ();
    };
}
